package com.ruoyi.web.controller.api;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.estate.Resident;
import com.ruoyi.system.service.estate.IResidentService;
import com.ruoyi.common.annotation.Anonymous;

/**
 * 住户信息API Controller
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/api/resident")
public class ResidentApiController extends BaseController {
    
    @Autowired
    private IResidentService residentService;
    
    /**
     * 获取当前登录用户的住户信息
     */
    @Anonymous
    @GetMapping("/info")
    public AjaxResult getResidentInfo() {
        try {
            // 获取当前登录用户ID
            Long userId = SecurityUtils.getUserId();
            
            // 查询用户关联的住户信息
            Resident resident = new Resident();
            resident.setUserId(userId);
            List<Resident> residents = residentService.selectResidentList(resident);
            
            if (residents.isEmpty()) {
                return AjaxResult.success(null);
            }
            
            return AjaxResult.success(residents.get(0));
        } catch (Exception e) {
            // 用户未登录或会话过期，返回空
            return AjaxResult.success(null);
        }
    }
    
    /**
     * 更新住户信息
     */
    @Anonymous
    @PutMapping("/info")
    public AjaxResult updateResidentInfo(@RequestBody Resident resident) {
        try {
            // 获取当前登录用户ID
            Long userId = SecurityUtils.getUserId();
            
            // 查询用户关联的住户信息
            Resident query = new Resident();
            query.setUserId(userId);
            List<Resident> residents = residentService.selectResidentList(query);
            
            if (residents.isEmpty()) {
                return AjaxResult.error("未找到您的住户信息");
            }
            
            // 确保只能修改自己的信息
            Resident existingResident = residents.get(0);
            resident.setResidentId(existingResident.getResidentId());
            resident.setUserId(userId);
            
            // 不允许修改的字段
            resident.setHouseId(existingResident.getHouseId());
            resident.setResidentType(existingResident.getResidentType());
            resident.setStatus(existingResident.getStatus());
            resident.setDelFlag(existingResident.getDelFlag());
            
            return toAjax(residentService.updateResident(resident));
        } catch (Exception e) {
            return AjaxResult.error("更新住户信息失败：" + e.getMessage());
        }
    }
    
    /**
     * 绑定住户信息
     */
    @Anonymous
    @PostMapping("/bind")
    public AjaxResult bindResident(@RequestBody Resident resident) {
        try {
            // 获取当前登录用户ID
            Long userId = SecurityUtils.getUserId();
            
            // 检查是否已经绑定住户
            Resident query = new Resident();
            query.setUserId(userId);
            List<Resident> existingResidents = residentService.selectResidentList(query);
            
            if (!existingResidents.isEmpty()) {
                return AjaxResult.error("您已绑定住户信息，不能重复绑定");
            }
            
            // 设置用户ID
            resident.setUserId(userId);
            
            // 设置默认值
            resident.setStatus("0"); // 正常状态
            resident.setDelFlag("0"); // 未删除
            
            return toAjax(residentService.insertResident(resident));
        } catch (Exception e) {
            return AjaxResult.error("绑定住户信息失败：" + e.getMessage());
        }
    }
    
    /**
     * 解绑住户信息
     */
    @Anonymous
    @PostMapping("/unbind")
    public AjaxResult unbindResident() {
        try {
            // 获取当前登录用户ID
            Long userId = SecurityUtils.getUserId();
            
            // 查询用户关联的住户信息
            Resident query = new Resident();
            query.setUserId(userId);
            List<Resident> residents = residentService.selectResidentList(query);
            
            if (residents.isEmpty()) {
                return AjaxResult.error("未找到您的住户信息");
            }
            
            // 解除绑定（将userId设为null）
            Resident resident = residents.get(0);
            resident.setUserId(null);
            
            return toAjax(residentService.updateResident(resident));
        } catch (Exception e) {
            return AjaxResult.error("解绑住户信息失败：" + e.getMessage());
        }
    }
} 